﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace AppDesigner.XamlDom
{
    public static class XamlTypeFinder
    {
        /// <summary>
        /// 根据Xaml中的名称获取相应的类型
        /// </summary>
        /// <param name="xmlNamespace"></param>
        /// <param name="localName"></param>
        /// <returns></returns>
        public static Type GetClrType(string xmlNameSpace, string localName)
        {
            foreach (AssemblyInfo assemblyInfo in AssemblyLoader.assemblyInfos)
            {
                Assembly runtimeAssembly = assemblyInfo.RuntimeAssembly;
                XamlNamespace xamlNameSpace = assemblyInfo.XamlNameSpaces.Where(x => x.XmlNamespace.Equals(xmlNameSpace)).FirstOrDefault();
                if (xamlNameSpace != null)
                {
                    foreach (string clrNameSpace in xamlNameSpace.ClrNamespaces)
                    {
                        Type type = runtimeAssembly.GetType(clrNameSpace + "." + localName);
                        if (type != null)
                        {
                            return type;
                        }
                    }
                }
            }
            return null;
        }

        /// <summary>
        /// 根据ClrNamespace 找到xmlnamespace
        /// </summary>
        /// <param name="assembly"></param>
        /// <param name="namespace"></param>
        /// <returns></returns>
        public static string GetXmlNamespaceFor(Assembly assembly, string clrNamespace)
        {
            foreach (AssemblyInfo assemblyInfo in AssemblyLoader.assemblyInfos)
            {
                if (assemblyInfo.AssemblyName.Equals(assembly.GetName().Name))
                {
                    foreach (XamlNamespace xamlNameSpace in assemblyInfo.XamlNameSpaces)
                    {
                        string xmlNamespace;
                        if ((xmlNamespace = xamlNameSpace.ClrNamespaces.Where(x => x.Equals(clrNamespace)).FirstOrDefault<string>()) != null)
                        {
                            return xmlNamespace;
                        }
                    }
                }
            }
            return null;
        }
    }
}
